package org.gatorojo.dao.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.sql.DataSource;

import javax.naming.InitialContext;
import org.gatorojo.enumerations.ConnectionType;

public class ConnectionManager {		
	public static Connection openConnection() { 
		Connection connection = null;
		
		try	{
			ConnectionType connectionType = ConnectionType.valueOf(ConnectionProperties.getProperty("connection.type", true));
			switch(connectionType) {
			case JDBC:
				String driverName = ConnectionProperties.getProperty("jdbc.driver", true);
				String url = ConnectionProperties.getProperty("jdbc.url", true);
				String username = ConnectionProperties.getProperty("jdbc.username", true);
				String password = ConnectionProperties.getProperty("jdbc.password", true);
				
				Class.forName(driverName).newInstance();	      
				connection = DriverManager.getConnection(url, username, password);            		    
				break;
			case JNDI:				
				String name = ConnectionProperties.getProperty("jndi.name", true);			
				InitialContext initialContext = new InitialContext();
			    DataSource dataSource = (DataSource) initialContext.lookup(name);
			    connection =  dataSource.getConnection();				
				break;
			default:
				return null;
			}			
		} catch (Exception e) {
	    	System.out.println("Error when opening connection:" + e.getMessage());		    	
	    }
		return connection;
	}
	
	public static void closeConnection(Connection conexion) {
		try	{
    		conexion.close();            
	    } catch (Exception e) {
	    	System.out.println("Error when closing connection:" + e.getMessage());	    	
	    }			
	}
}